import { deepClone } from "fast-json-patch";
import { getValueByPointer } from "fast-json-patch";
import { applyOperation, type Operation } from "fast-json-patch";

export function revertOperation(
  document: any,
  newDocument: any,
  operation: Operation
) {
  const { op, path } = operation;
  if (op === "add") {
    applyOperation(newDocument, { op: "remove", path });
  } else if (op === "remove") {
    const oldValue = deepClone(getValueByPointer(document, path));
    applyOperation(newDocument, { op: "add", path, value: oldValue });
  } else if (op === "replace") {
    const oldValue = deepClone(getValueByPointer(document, path));
    applyOperation(newDocument, { op: "replace", path, value: oldValue });
  } else {
    throw new Error(`撤销更新失败：无法逆转 ${op} 运算`);
  }
}
